﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RedmineHelper
{
    public partial class FormAccounts : Form
    {
        public FormAccounts()
        {
            InitializeComponent();
        }

        private void FormAccounts_Load(object sender, EventArgs e)
        {
            Reload();
        }

        private void Reload()
        {
            lst.Items.Clear();
            IList<account> accounts = AccountHelper.LoadAccounts();
            foreach (var a in accounts)
            {
                ListViewItem item = new ListViewItem(a.host);
                item.SubItems.Add(a.username);
                lst.Items.Add(item);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            FormAccount fa = new FormAccount();
            fa.ShowDialog();
            Reload();
        }

        private void lst_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (lst.SelectedIndices.Count > 0)
            {
                IList<account> accounts = AccountHelper.LoadAccounts();
                ListViewItem item = lst.SelectedItems[0];
                var al = from a in accounts where a.host == item.Text select a;
                if (al.Count() > 0)
                {
                    account a = al.First();
                    FormAccount fa = new FormAccount();
                    fa.SetText(a);
                    fa.ShowDialog();
                }
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (lst.SelectedIndices.Count > 0)
            {
                IList<account> accounts = AccountHelper.LoadAccounts();
                ListViewItem item = lst.SelectedItems[0];
                var al = from a in accounts where a.host == item.Text select a;
                if (al.Count() > 0)
                {
                    account a = al.First();
                    accounts.Remove(a);
                    AccountHelper.SaveAccounts(accounts);
                }
            }
        }
    }
}
